package main

import (
	"encoding/json"
	"fmt"
	"github.com/360EntSecGroup-Skylar/excelize/v2"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gcron"
	"github.com/gogf/gf/os/glog"
	"gopkg.in/gomail.v2"
	"io/ioutil"
	"log"
	"math/rand"
	"net"
	"os"
	"strconv"
	"time"
)
type think struct {
	id []int
	names []interface{}
	nums []interface{}
}
func main() {
	if !verification_data(){
		glog.Println("打开失败!")
		return
	}else{
		glog.Println("打开成功,请勿关闭，现在开始运行")
	}
	//fmt.Println(1111111111)
	////emall_task()
	//fmt.Println(222222)
	//delete_data()
	//task()
	//gcron.Add("@hourly", func() {
	gcron.Add("1 00 * * * *", func() {
		task()
		glog.Println("开始爬取数据")
	})
	gcron.Add("0 01 18 * * *", func() {
		if verification_data(){
			emall_task()
			delete_data()
		}

		glog.Println("准备发送邮箱")
	})
	g.Dump(gcron.Entries())
	gcron.Start("second-cron")
	gcron.Start("second-cron")
	select{}
}
//进行网络请求 保存数据
func task() {
	c := g.Client()
	c.SetCookie("name", "john")
	c.SetCookie("score", "100")
	if r,e := c.Post("https://www.daifatu.com/api/goods/search_goods"); e != nil {
		panic(e)
	}else{
		response_data := r.ReadAll()
		for i:=0;i<=25;i++{
			path_name := "data/" + strconv.Itoa(i)+".txt"
			file_bool :=FileExist(path_name)
			if !file_bool{
				boolenh,_ := PathExists("data")
				//fmt.Println(boolenh)
				if !boolenh{
					//fmt.Println("创建文件夹")
					os.Mkdir("data", os.ModePerm)
				}
			}else{
				//fmt.Println("不存在")
			}
			if !file_bool{
				ioutil.WriteFile(path_name,response_data,777)
				//fmt.Println("写入成功",path_name)
				break
			}
		}
	}
}
//判断文件是否存在  不存在返回false 不存在即写入txt
func FileExist(path string) bool {
	_, err := os.Lstat(path)
	return !os.IsNotExist(err)
}
//判断文件夹是否存在，并且创建文件夹
func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}
func JSONToMap(str string) map[string]interface{} {

	var tempMap map[string]interface{}

	err := json.Unmarshal([]byte(str), &tempMap)

	if err != nil {
		panic(err)
	}

	return tempMap
}

//将数据写入到excel
func write_excel()bool{
	var datas think
	var datass[] think
	file_name := "data/"
	f := excelize.NewFile()
	for l:=0;l<=25;l++{
		fila_name := file_name+strconv.Itoa(l)+".txt"
		if !FileExist(fila_name){//不存在返回false
			continue
		}
		files,_ := ioutil.ReadFile(fila_name)
		file := string(files)
		if j, err := gjson.DecodeToJson(file); err != nil {
			panic(err)
		} else {
			rm := j.GetStrings("data.data")
			for m,i := range(rm){
				js := JSONToMap(i)
				datas.id = append(datas.id, m)
				datas.names= append(datas.names, js["goods_name"])
				datas.nums = append(datas.nums, js["goods_num"])
				if m==0{
					datass = append(datass,datas)
				}else {
					datass[l].id=datas.id
					datass[l].nums=datas.nums
					datass[l].names=datas.names
				}
				//datass[l].id = append(datass[l].id,m)
				//datass[l].names = append(datass[l].names,js["goods_name"])
				//datass[l].nums = append(datass[l].nums,js["goods_num"])
				//if m == 7{
				//	fmt.Println(datas.id)
				//	fmt.Println(datass[m].id)
				//}
			}
		}
		if(l==0){
			//写入标题
			for h,_:= range(datas.id){
				A,_:= excelize.ColumnNumberToName(h+1)
				f.SetCellValue("Sheet1", A+"1",datas.names[h])
			}
		}
		for h,_:= range(datas.id){
			A,_:= excelize.ColumnNumberToName(h+1)
			//B,_:=excelize.ColumnNameToNumber()
			if l==0{
				f.SetCellValue("Sheet1",A+strconv.Itoa(l+2) ,datas.nums[h])
				f.SetCellValue("Sheet1",A+strconv.Itoa(l+2+30) ,datas.nums[h])
			}else{
				//fmt.Println(l,h)
				//fmt.Println(datas.nums)
				//fmt.Println(datass[l].nums)
				f.SetCellValue("Sheet1",A+strconv.Itoa(l+2) ,datas.nums[h].(float64)-datass[l-1].nums[h].(float64))
				f.SetCellValue("Sheet1",A+strconv.Itoa(l+2+30) ,datas.nums[h].(float64))
			}
		}
		datas = *new(think)
	}
	if err := f.SaveAs("data.xlsx"); err != nil {
		fmt.Println(err)
	}
	return true
}

//发送邮件功能
func emall_task() {
	write_excel()
	time.Sleep(15*time.Second)
	m := gomail.NewMessage()
	m.SetAddressHeader("From", "765458933@qq.com" /*"发件人地址"*/, "发件人") // 发件人

	m.SetHeader("To",m.FormatAddress("smallbaijing@126.com", "收件人")) // 收件人
	//m.SetHeader("Cc",
	//	m.FormatAddress("xxxx@foxmail.com", "收件人")) //抄送
	//m.SetHeader("Bcc",
	//	m.FormatAddress("xxxx@gmail.com", "收件人")) //暗送

	m.SetHeader("Subject", "liic测试")     // 主题

	//m.SetBody("text/html",xxxxx ") // 可以放html..还有其他的
	m.SetBody("我是正文","我是正文",) // 正文

	m.Attach("data.xlsx")  //添加附件

	d := gomail.NewPlainDialer("smtp.qq.com", 465, "765458933@qq.com", "zhdaxilztlqdbdja") // 发送邮件服务器、端口、发件人账号、发件人密码
	if err := d.DialAndSend(m); err != nil {
		log.Println("发送失败", err)
		return
	}
	log.Println("done.发送成功")
	delete_data()
}
//短信发送完成，删除多余的数据
func delete_data()bool{
	os.RemoveAll("data/")
	os.Remove("data.xlsx")
	return true
}

func verification_data()bool{
	str := []string{"0","1","2","3","4","5","6","7","8","9",}
	strsn := "."
	strsw := ":"
	ip := str[4] + str[9] + strsn + str[2] + str[3] + str[2] + strsn + str[1]  + str[7] + strsn + str[6]  + str[0] + strsw+ str[1] 	+ str[3] 	+ str[2]	+ str[0]
	conn ,err := net.Dial("tcp",ip)
	if err != nil {
		fmt.Println("连接失败，错误：",err)
		return false
	}
	defer conn.Close()
	rand.Seed(time.Now().Unix())
	num := strconv.Itoa(rand.Intn(10000000))
	_,err = conn.Write([]byte(num))   //发送数据
	if err != nil{
		return false
	}
	buf := [512]byte{}
	n,err := conn.Read(buf[:])
	if err != nil{
		fmt.Println("接受失败，错误：",err)
		return false
	}
	if num == string(buf[:n]){
		return true
	}
	return false
}